﻿// Decompiled with JetBrains decompiler
// Type: MCM.Implementation.BaseSettingsJsonConverter
// Assembly: MCMv5, Version=5.10.2.0, Culture=neutral, PublicKeyToken=null
// MVID: 7AB326B9-B2B4-41C2-9177-68E944071101
// Assembly location: D:\steam\steamapps\workshop\content\261550\2859238197\bin\Win64_Shipping_Client\MCMv5.dll

using BUTR.DependencyInjection.Logger;
using MCM.Abstractions;
using MCM.Abstractions.Base;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

#nullable enable
namespace MCM.Implementation
{
  public sealed class BaseSettingsJsonConverter : JsonConverter
  {
    private readonly IBUTRLogger _logger;
    private readonly Action<string, object?> _addSerializationProperty;
    private readonly Action _clearSerializationProperties;

    public BaseSettingsJsonConverter(
      IBUTRLogger logger,
      Action<string, object?> addSerializationProperty,
      Action clearSerializationProperties)
    {
      this._logger = logger;
      this._addSerializationProperty = addSerializationProperty;
      this._clearSerializationProperties = clearSerializationProperties;
    }

    public override bool CanConvert(Type objectType)
    {
      return objectType.IsSubclassOf(typeof (BaseSettings));
    }

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
      if (!(value is BaseSettings settings))
        return;
      JObject jobject = new JObject();
      foreach (ISettingsPropertyDefinition propertyDefinition in settings.GetAllSettingPropertyDefinitions())
      {
        if (propertyDefinition.SettingType != SettingType.Button)
          jobject.Add(propertyDefinition.Id, propertyDefinition.PropertyReference.Value == null ? (JToken) null : JToken.FromObject(propertyDefinition.PropertyReference.Value, serializer));
      }
      jobject.WriteTo(writer);
    }

    public override object? ReadJson(
      JsonReader reader,
      Type objectType,
      object? existingValue,
      JsonSerializer serializer)
    {
      if (!(existingValue is BaseSettings settings))
        return existingValue;
      try
      {
        JObject jobject = JObject.Load(reader);
        this._clearSerializationProperties();
        foreach (ISettingsPropertyDefinition propertyDefinition in settings.GetAllSettingPropertyDefinitions())
        {
          JToken jtoken;
          if (propertyDefinition.SettingType != SettingType.Button && jobject.TryGetValue(propertyDefinition.Id, out jtoken))
          {
            this._addSerializationProperty(jtoken.CreateReader().Path, propertyDefinition.PropertyReference.Value);
            propertyDefinition.PropertyReference.Value = jtoken.ToObject(propertyDefinition.PropertyReference.Type, serializer);
          }
        }
        this._clearSerializationProperties();
      }
      catch (Exception ex)
      {
        this._logger.LogError(ex, "Error while deserializing Settings");
      }
      return existingValue;
    }
  }
}
